﻿using MovingChame.Web.Helpers;
using MovingChame.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MovingChame.Web.Infrastructure
{
    public class SuggestedTourProvider : ISuggestedTourProvider
    {
        private static SuggestedTourProvider current;
        public static SuggestedTourProvider Current
        {
            get
            {
                if (current == null) current = new SuggestedTourProvider();
                return current;
            }
        }

        #region Configuration
        private string applicationName;
        public string ApplicationName
        {
            get { return applicationName; }
            set { applicationName = value; }
        }

        private string connectionStringName;
        private string providerName;
        private MovingChameModelContainer db;

        public void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            providerName = name;

            if (config["applicationName"] != null)
                applicationName = config["applicationName"];

            if (config["connectionStringName"] != null)
            {
                connectionStringName = config["connectionStringName"];
                db = new MovingChameModelContainer();
                db.Database.Connection.ConnectionString = ConfigurationHelper.GetConnectionString(connectionStringName);
            }
            else
                db = new MovingChameModelContainer();
        }

        private SuggestedTourProvider()
        {
            Initialize("SuggestedTourProvider", new System.Collections.Specialized.NameValueCollection());
        }
        #endregion

        #region Interface Methods
        public int AddSuggestedTour(int userId, int user1Id, int tourId)
        {
            var newSuggestedTour = new SuggestedTour
            {
                UserId = userId,
                UserId1 = user1Id,
                AbstractTourId = tourId
            };
            db.SuggestedTours.Add(newSuggestedTour);
            db.SaveChanges();
            return newSuggestedTour.Id;
        }

        public bool RemoveSuggestedTour(int userId, int user1Id, int tourId)
        {
            var removedTour = db.SuggestedTours.Where(o => o.UserId == userId).Where(o => o.UserId1 == user1Id).SingleOrDefault(o => o.AbstractTourId == tourId);
            if (removedTour == null)
                return false;
            db.SuggestedTours.Remove(removedTour);
            db.SaveChanges();
            return true;
        }

        public IQueryable<AbstractTour> GetSuggestedTours(int userId1)
        {
            return db.SuggestedTours.Where(o => o.UserId1 == userId1).Select(o => o.AbstractTour);
        }
        #endregion
    }
}